      1  import java.awt.Rectangle;

      2

      3  /**

      4     This example demonstrates the difference between copying

      5     numbers and object references.

      6  */

      7  public class CopyDemo

      8  {

      9     public static void main(String[] args)

     10     {

     11        // Declare two object variables and copy the first into the second

     12

     13        Rectangle box = new Rectangle(5, 10, 20, 30);

     14        Rectangle box2 = box;

     15

     16        // Both variables refer to the same object

     17

     18        System.out.print("box: ");

     19        System.out.println(box);

     20        System.out.print("box2: ");

     21        System.out.println(box2);

     22

     23        System.out.println("Mutating box2");

     24        box2.translate(15, 25);

     25

     26        // Both variables refer to the mutated object

     27

     28        System.out.print("box: ");

     29        System.out.println(box);

     30        System.out.print("box2: ");

     31        System.out.println(box2);

     32

     33        // Declare two number variables and copy the first into the second

     34

     35        int luckyNumber = 13;

     36        int luckyNumber2 = luckyNumber;

     37

     38        System.out.print("luckyNumber: ");

     39        System.out.println(luckyNumber);

     40        System.out.print("luckyNumber2: ");

     41        System.out.println(luckyNumber2);

     42

     43        System.out.println("Changing luckyNumber2");

     44        luckyNumber2 = 12;

     45

     46        // Only the second number changes.

     47

     48        System.out.print("luckyNumber: ");

     49        System.out.println(luckyNumber);

     50        System.out.print("luckyNumber2: ");

     51        System.out.println(luckyNumber2);

     52     }

     53  }

     54

     55

     56